package com.cskaoyan.user.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dto.KaptchaCodeRequest;
import com.cskaoyan.user.dto.KaptchaCodeResponse;
import com.cskaoyan.user.dto.UserRegisterRequest;
import com.cskaoyan.user.dto.UserRegisterResponse;
import com.cskaoyan.user.dto.bo.UserRegisterBo;
import com.cskaoyan.user.service.UserRegisterService;
import com.cskaoyan.user.service.impl.KaptchaServiceImpl;

/**
 * @author zyf
 * @since 2022/06/17 17:28
 */
@RestController
@RequestMapping("/user")
public class RegisterController {

    @Autowired
    UserRegisterService userRegisterService;
    @Autowired
    KaptchaServiceImpl kaptchaService;
    @PostMapping("/register")
    public ResponseData register(@RequestBody UserRegisterBo userRegisterBo, HttpServletRequest request){

        String captcha = userRegisterBo.getCaptcha();
        //验证码校验
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        KaptchaCodeResponse response = kaptchaService.validateKaptchaCode(kaptchaCodeRequest);

        String code = response.getCode();
        if (!code.equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }


        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setEmail(userRegisterBo.getEmail());
        userRegisterRequest.setUserName(userRegisterBo.getUserName());
        userRegisterRequest.setUserPwd(userRegisterBo.getUserPwd());

        UserRegisterResponse userRegisterResponse=userRegisterService.register(userRegisterRequest);
        if (userRegisterResponse.getCode().equals(UserRetCode.SUCCESS.getCode())){
            return new ResponseUtil<>().setData(null);
        }

        return new ResponseUtil<>().setErrorMsg(userRegisterResponse.getCode());



    }
}
